package org.ly.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.ly.dao.TempMessage;
import org.ly.dao.TempMessageRepository;
import org.ly.util.DateUtil;
import org.ly.util.LogUtil;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class TempMessageService {
    private final TempMessageRepository tempMessageRepository;

    public TempMessageService(TempMessageRepository tempMessageRepository) {
        this.tempMessageRepository = tempMessageRepository;
    }

    public List<TempMessage> eopsMetricMessageResolve(String message) {
        List<TempMessage> tempMessages = new ArrayList<>();
        try {
            message = "[" + message + "]";
            JSONArray jsonArray = JSON.parseArray(message);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONArray innerArray = jsonArray.getJSONArray(i);
                for (int j = 0; j < innerArray.size(); j++) {
                    JSONObject jsonObject = innerArray.getJSONObject(j);
                    TempMessage tempMessage = new TempMessage();
                    tempMessage.setCollectTime(new Timestamp(DateUtil.string2timestamp(jsonObject.getString("COLLECTTIME"))));
                    tempMessage.setMessageTopic("EOPS_METRIC");
                    tempMessage.setCompKey(jsonObject.getString("COMPKEY"));
                    tempMessage.setHostIp(jsonObject.getString("HOSTIP"));
                    tempMessage.setCompType(jsonObject.getString("COMPTYPE"));
                    tempMessage.setRawMessage(jsonObject.toJSONString());
                    tempMessages.add(tempMessage);
                }

            }
//            tempMessageRepository.saveAll(tempMessages);
        } catch (Exception e) {
            LogUtil.logError("error parsed message：" + message + e.getMessage(), e);
        }
        return tempMessages;
    }

    public List<TempMessage> eopsConfigMessageResolve(String message) {
        List<TempMessage> tempMessages = new ArrayList<>();
        try {
            JSONObject jsonObject = JSON.parseObject(message);
            TempMessage tempMessage = new TempMessage();
            tempMessage.setCollectTime(new Timestamp(DateUtil.string2timestamp(jsonObject.getString("COLLECTTIME"))));
            tempMessage.setMessageTopic("EOPS_CONFIG");
            tempMessage.setCompKey(jsonObject.getString("COMPKEY"));
            tempMessage.setHostIp(jsonObject.getString("HOSTIP"));
            tempMessage.setCompType(jsonObject.getString("COMPTYPE"));
            tempMessage.setRawMessage(jsonObject.toJSONString());
            tempMessages.add(tempMessage);
//            tempMessageRepository.saveAll(tempMessages);
        } catch (Exception e) {
            LogUtil.logError("error parsed message：" + message + e.getMessage(), e);
        }
        return tempMessages;
    }
}
